import axios,{ AxiosError, type Method } from 'axios'
import { getToken } from './auth'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const instance = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 10000,
})
type Data<T> = {
  code: number
  message: string
  data: T
}

//请求拦截器
instance.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    ElMessage.error(error.response.data.msg);
    //401处理
    if (error.response.status === 401) {
      // 1. 跳转到登录
      const router = useRouter()
      router.push('/login')
      // 2. 清空用户数据
      const store = useUserStore()
      store.clearUserInfo()
    }
    return Promise.reject(error)
  },
)


//响应拦截器
instance.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    ElMessage.error(error.response.data.msg);
    return Promise.reject(error)
  },
)


// 4. 请求工具函数
const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  return instance.request<T,Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

export { request,instance}